#include <string.h>
#include <stdlib.h>
#include "futbolistasLoad.h"

int futbolistacount;

int loadFutbolistas(char const *filename,struct FutbolistaVars **data_ptr){
	FILE *ptr_file;///create FILE pointer
	ptr_file=fopen(filename,"r");///open file specified in *filename
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;///used to allocate buffer length
	int numlines=getFileInfo(ptr_file,&maxlinelen);///used to allocate futbolistas array size
	futbolistacount=numlines;
	struct FutbolistaVars *data;
	data=(struct FutbolistaVars*) calloc(numlines,sizeof(struct FutbolistaVars));///allocate futbolista array
	char *buf=(char*) malloc(maxlinelen*sizeof(char));///allocate buffer size
	char *tmp=(char*) malloc(20*sizeof(char));

	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);///load a line to buffer
		sscanf(strtok(buf,"-"), "%d", &data[i].playerID);
		sscanf(strtok(NULL,"-"), "%d", &data[i].teamID);
		strcpy(data[i].name,strtok(NULL,"-"));
		sscanf(strtok(NULL,"-"), "%d", &data[i].price);
		sscanf(strtok(NULL,"\n"), "%d", &data[i].value);
	}
	free(buf);
	fclose(ptr_file);
	*data_ptr=data;
	return 0;
}

int writeFutbolistas(char const *filename,struct FutbolistaVars *data){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	///loop through futbolistas
	for(int i=0;i<futbolistacount;i++){
		///print a line
		fprintf(ptr_file,"%02d-%03d-%s-%d-%d\n",data[i].playerID,data[i].teamID,data[i].name,data[i].price,data[i].value);
	}
	fclose(ptr_file);
	free(data);
	return 0;
}

void addFutbolista(struct FutbolistaVars n,struct FutbolistaVars **data_ptr){
	///reallocate futbolista array size and increment futbolistacount
	struct FutbolistaVars *data;
	data=(struct FutbolistaVars*) realloc(*data_ptr,++futbolistacount*sizeof(struct FutbolistaVars));
	data[futbolistacount-1]=n;
	*data_ptr=data;
}

void rmFutbolista(int index,struct FutbolistaVars **data_ptr){
	struct FutbolistaVars *data=(struct FutbolistaVars*) calloc(futbolistacount-1,sizeof(struct FutbolistaVars));///allocate new array with one less element
	if(index!=0){
		memcpy(data,*data_ptr,index*sizeof(struct FutbolistaVars));
	}
	//copy everything after index
	if(index < futbolistacount){
		memcpy(data + index,*data_ptr + index + 1,(futbolistacount - index - 1)*sizeof(struct FutbolistaVars));
	}
	futbolistacount--;
	free(*data_ptr);
	*data_ptr=data;
}
